//
//  CatchCrash.m
//  DanoneEA
//
//  Created by Jery on 2016/10/30.
//  Copyright © 2016年 翔傲科技. All rights reserved.
//

#import "CatchCrash.h"

static NSString *const DBNAME_LOG = @"danone_crash";

@implementation CatchCrash

void uncaughtExceptionHandler(NSException *exception)
{
    // 异常的堆栈信息
    NSArray *stackArray = [exception callStackSymbols];
    // 出现异常的原因
    NSString *reason = [exception reason];
    // 异常名称
    NSString *name = [exception name];
    
    NSDate *nowDate = [NSDate date];
    NSString *exceptionInfo = [NSString stringWithFormat:@"\n%@\nException reason：%@\nException name：%@\nException stack：%@",nowDate,name, reason, stackArray];
    DDLogDebug(@"%@", exceptionInfo);
    
    NSMutableArray *tmpArr = [NSMutableArray arrayWithArray:stackArray];
    [tmpArr insertObject:reason atIndex:0];
    
    [CatchCrash appString:exceptionInfo];
}

+(void) appString:(NSString *)exceptionInfo
{

    NSDateFormatter * dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [dateFormater stringFromDate:[NSDate date]];
    
    NSString * logFileNameStr = [NSString stringWithFormat:@"%@ %@.log",DBNAME_LOG,dateString];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),logFileNameStr];
    
    NSLog(@"filePath ==== %@",filePath);  
    
    BOOL isExit = [fileManager fileExistsAtPath:filePath];

    if (!isExit) {
        DDLogDebug(@"%@",@"文件不存在");
        [exceptionInfo writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    }
    
    NSFileHandle  *outFile;
    NSData *buffer;

    outFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
    if(outFile == nil)
    {
        NSLog(@"Open of file for writing failed");
    }
    
    //找到并定位到outFile的末尾位置(在此后追加文件)
    [outFile seekToEndOfFile];
    
    //读取inFile并且将其内容写到outFile中
    NSString *bs = [NSString stringWithFormat:@"%@",exceptionInfo];
    buffer = [bs dataUsingEncoding:NSUTF8StringEncoding];
    
    [outFile writeData:buffer];
    
    //关闭读写文件
    [outFile closeFile];
    
}


@end
